import React from "react";
import PropTypes from 'prop-types';
import {
    Avatar,
    Badge,
    Button,
    Card,
    Col,
    Comment,
    Descriptions,
    Input,
    PageHeader,
    Radio,
    Rate,
    Row,
    Tag,
    message,
    Popconfirm, Spin
} from "antd";
import {CommentService, ShopService, UserService} from "../eosjs/EosService";
import {Link} from "react-router-dom";
import './UserInfo.less'
import {DeleteOutlined, EditOutlined} from "@ant-design/icons";

class UserInfo extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            avatarMap: new Map(),
            isMyself: this.props.match.params.userName === localStorage.getItem("name_account"),
            userName: this.props.match.params.userName,
            spinning: true,
            userInfo: {
                isExist: false,
                nickName: "",
                isMerchant: 1,
                avatarUrl: "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png",
                address: "",
                cellPhone: "",
            },
            userComment: [
                {
                    "cid": 2,
                    "user": "",
                    "visible": 0,
                    "content": {"text": "", "tags": [], "rate": 0},
                    "replyid": 0,
                    "shopid": 1,
                    "shop": {
                        "sid": 1,
                        "user": "haidilao",
                        "is_checked": 0,
                        "description": "全国连锁，服务周到",
                        "picture_url": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589348618871&di=850ee3aea6bfe86a0378862bf47f1458&imgtype=0&src=http%3A%2F%2Fp5.pccoo.cn%2Fnews%2F20161012%2F2016101210474854472158.jpg",
                        "shop_name": "",
                        "tag": "火锅",
                        "address": "XX路XX号",
                        "goodsid": [
                            1,
                            2
                        ]
                    }
                }
            ],
        };

    }

    componentDidMount() {
        this.getUserInfo();
        this.getUserComment();
        // console.log(this.state)
    }

    render() {
        return (
            <div className="userInfo">
                <PageHeader
                    className="site-page-header"
                    onBack={() => null}
                    title="用户信息"
                />
                <Row gutter={24}>
                    <Col span={1}></Col>
                    <Col span={22}>
                        <Descriptions title="" layout="vertical" bordered>
                            <Descriptions.Item label="用户名">{this.state.userName}</Descriptions.Item>
                            <Descriptions.Item label="昵称">
                                <Input placeholder="请输入昵称" value={this.state.userInfo.nickName}
                                       onChange={this.nickNameChange} readOnly={!this.state.isMyself}/>
                            </Descriptions.Item>
                            <Descriptions.Item label="是否为商家">
                                <Radio.Group onChange={this.merchantChange} value={this.state.userInfo.isMerchant}
                                             disabled={!this.state.isMyself}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={2}>否</Radio>
                                </Radio.Group>
                            </Descriptions.Item>
                            <Descriptions.Item label="头像图片链接">
                                <Avatar
                                    src={this.state.userInfo.avatarUrl}
                                    alt={this.state.userName}
                                />
                                <Input placeholder="请输入头像图片链接" style={{width: "90%"}} value={this.state.userInfo.avatarUrl}
                                       onChange={this.avatarUrlChange} readOnly={!this.state.isMyself}/>
                            </Descriptions.Item>
                            <Descriptions.Item label="地址"><Input placeholder="请输入地址" value={this.state.userInfo.address}
                                                                 onChange={this.addressChange}
                                                                 readOnly={!this.state.isMyself}/></Descriptions.Item>
                            <Descriptions.Item label="手机号"><Input placeholder="请输入手机号"
                                                                  value={this.state.userInfo.cellPhone}
                                                                  onChange={this.cellPhoneChange}
                                                                  readOnly={!this.state.isMyself}/></Descriptions.Item>
                        </Descriptions>
                        {this.state.isMyself ? <Button type={"primary"} onClick={this.commitUserInfo}>{!this.state.userInfo.isExist ? "添加用户信息" : "修改用户信息"}</Button> : null}
                    </Col>
                    <Col span={1}></Col>
                </Row>
                <Spin tip="评论加载中" spinning={this.state.spinning}>
                <Row gutter={24}>
                    <Col span={1}></Col>
                    <Col span={22}>
                        <Card
                            title="用户点评" bordered={false} style={{width: "100%"}}
                        >
                            {this.state.userComment.map((value, index) => {
                                if (value.replyid !== 0) {
                                    return;
                                }
                                return (
                                    <Comment key={index}
                                             actions={this.state.isMyself ? [
                                                 <Link to={{
                                                     pathname: "/editComment",
                                                     state: {
                                                         replyId: 0,
                                                         cid: value.cid,
                                                         shopId: value.shop.sid,
                                                         editMode: "update"
                                                     }
                                                 }}>
                                                     <Button shape="circle" icon={<EditOutlined/>}
                                                             disabled={!value.visible}>
                                                     </Button>
                                                 </Link>,
                                                 <Popconfirm placement="top" title={"是否删除该评论？"}
                                                             onConfirm={this.eraseUserComment.bind(this, value)}
                                                             okText="确定" cancelText="取消">
                                                 <Button shape="circle" icon={<DeleteOutlined/>} disabled={!value.visible}/>
                                                 </Popconfirm>
                                             ] : []}
                                             author={"用户名：" + value.user + " / 评论店铺：" + value.shop.shop_name}
                                             avatar={
                                                 <Avatar
                                                     src={this.state.userInfo.avatarUrl}
                                                     alt={value.user}
                                                     onClick={() => this.props.history.push("/user/" + value.user)}
                                                 />
                                             }
                                             content={
                                                 <div>
                                                     <Rate disabled defaultValue={value.content.rate}/>
                                                     <br/>
                                                     <br/>
                                                     {value.content.tags.map((tagValue, tagId) => {
                                                         return <Tag key={tagId} color="default">{tagValue}</Tag>
                                                     })}
                                                     <br/>
                                                     <br/>
                                                     {value.content.text}
                                                 </div>
                                             }
                                    />);
                            })}
                        </Card>
                    </Col>
                    <Col span={1}></Col>
                </Row>
                <Row gutter={24}>
                    <Col span={1}></Col>
                    <Col span={22}>
                        <Card
                            title="用户回复" bordered={false} style={{width: "100%"}}
                        >
                            {this.state.userComment.map((value, index) => {
                                if (value.replyid === 0) {
                                    return;
                                }
                                return (
                                    <Comment key={index}
                                             actions={[
                                                 <Button shape="circle" icon={<EditOutlined/>}
                                                         disabled={!value.visible}>
                                                     <Link to={{
                                                         pathname: "/modifyComment",
                                                         state: {replyId: value.cid, shopId: this.state.sid}
                                                     }}>
                                                     </Link>
                                                 </Button>,
                                                 <Popconfirm placement="top" title={"是否删除该评论？"}
                                                             onConfirm={this.eraseUserComment.bind(this, value)}
                                                             okText="确定" cancelText="取消">
                                                 <Button shape="circle" icon={<DeleteOutlined/>} disabled={!value.visible}/>
                                                 </Popconfirm>
                                             ]}
                                             author={"用户名：" + value.user + " / 评论店铺：" + value.shop.shop_name}
                                             avatar={
                                                 <Avatar
                                                     src={this.state.userInfo.avatarUrl}
                                                     alt={value.user}
                                                     onClick={() => this.props.history.push("/user/" + value.user)}
                                                 />
                                             }
                                             content={
                                                 <div>
                                                     {value.content.text}
                                                 </div>
                                             }
                                    >
                                        <Comment
                                            author={"原评论用户名：" + value.replyComment.user + " / 评论店铺：" + value.shop.shop_name}
                                            avatar={
                                                <Avatar
                                                    // src={this.state.avatarMap.get(value.replyComment.user) === null ? "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" : this.state.avatarMap.get(value.replyComment.user)}
                                                    alt={value.replyComment.user}
                                                    onClick={() => this.props.history.push("/user/" + value.replyComment.user)}
                                                />
                                            }
                                            content={
                                                <div>
                                                    <Rate disabled defaultValue={value.replyComment.content.rate}/>
                                                    <br/>
                                                    <br/>
                                                    {value.replyComment.content.tags.map((tagValue, tagId) => {
                                                        return <Tag key={tagId} color="default">{tagValue}</Tag>
                                                    })}
                                                    <br/>
                                                    <br/>
                                                    {value.replyComment.content.text}
                                                </div>
                                            }
                                        />
                                    </Comment>);
                            })}
                        </Card>
                    </Col>
                    <Col span={1}></Col>
                </Row>
                </Spin>
            </div>
        );
    }

    getUserComment = () => {
        CommentService.getAllComments({user: this.state.userName}).then(res => {
            if (res.rows.length <= 0) {
                this.props.history.push("/error404");
                return;
            }
            let tempRes = res.rows;
            let tempTempRes = [];
            for (let i = 0; i < tempRes.length; i++) {
                ShopService.getShops({sid: tempRes[i].shopid}).then(shopRes => {
                    tempRes[i].shop = shopRes.rows[0];
                    CommentService.getComments(tempRes[i].shopid,{cid: tempRes[i].replyid}).then(res => {
                        tempRes[i].replyComment = res.rows[0];
                        try {
                            tempRes[i].content = JSON.parse(tempRes[i].content);
                            if (typeof (tempRes[i].content.tags) === "undefined") {
                                tempRes[i].content.tags = ["测试数据，无标签"];
                            }
                            if (typeof (tempRes[i].content.rate) === "undefined") {
                                tempRes[i].content.rate = 3;
                            }
                        } catch (e) {
                            tempRes[i].content = {text: tempRes[i].content, rate: 2, tags: ["测试数据,无标签"]};
                        }
                        // console.log(res.rows[0])
                        if (typeof (tempRes[i].replyComment) !== "undefined") {
                            try {
                                tempRes[i].replyComment.content = JSON.parse(tempRes[i].replyComment.content);
                                if (typeof (tempRes[i].replyComment.content.tags) === "undefined") {
                                    tempRes[i].replyComment.content.tags = ["测试数据，无标签"];
                                }
                                if (typeof (tempRes[i].content.rate) === "undefined") {
                                    tempRes[i].replyComment.content.rate = 3;
                                }
                            } catch (e) {
                                tempRes[i].replyComment.content = {
                                    text: tempRes[i].replyComment.content,
                                    rate: 2,
                                    tags: ["测试数据,无标签"]
                                };
                            }
                        }
                        tempTempRes.push(tempRes[i]);

                        this.setState({
                            userComment: tempTempRes,
                            spinning: false
                        })
                        // console.log(tempTempRes)
                    })
                });
            }
        })
    }
    eraseUserComment = (value) => {
        console.log(value)
        CommentService.eraseComment(value.shopid, value.cid).then(res => {
            if (res.status === true) {
                this.props.history.push("/user/" + localStorage.getItem("name_account"));
                message.success("评论删除成功！");
            } else {
                message.error("评论删除失败！");
            }
        })
    }
    getUserInfo = () => {
        // console.log(this.state)

        UserService.getUserInfo(this.state.userName).then(res => {
            // console.log("获取个人信息", this.state, res.rows)
            if (res.rows !== null) {
                // console.log(res.rows)
                this.setState({
                    userInfo: {
                        isExist: true,
                        nickName: res.rows.user_name,
                        isMerchant: res.rows.is_merchant ? 1 : 2,
                        avatarUrl: res.rows.avatar_url,
                        address: res.rows.address,
                        cellPhone: res.rows.phone_number,
                    },
                })
                console.log("获取个人信息", this.state, res.rows)
            }
        })
    }
    commitUserInfo = () => {
        const {nickName, isMerchant, avatarUrl, address, cellPhone} = this.state.userInfo;
        UserService.updateUserInfo(nickName, isMerchant === 1 ? true : false, avatarUrl, address, cellPhone, "").then(res => {
            if (res.status === true) {
                this.props.history.push("/user/" + localStorage.getItem("name_account"));
                message.success("用户信息修改成功！")
            } else {
                console.log(res)
                message.error("用户信息修改失败！")
            }
        })
    }
    nickNameChange = (e) => {
        let userInfo = this.state.userInfo;
        userInfo.nickName = e.target.value;
        this.setState({userInfo: userInfo});
    }
    merchantChange = (e) => {
        let userInfo = this.state.userInfo;
        userInfo.isMerchant = e.target.value;
        this.setState({userInfo: userInfo});
    }
    avatarUrlChange = (e) => {
        let userInfo = this.state.userInfo;
        userInfo.avatarUrl = e.target.value;
        this.setState({userInfo: userInfo});
    }
    addressChange = (e) => {
        let userInfo = this.state.userInfo;
        userInfo.address = e.target.value;
        this.setState({userInfo: userInfo});
    }
    cellPhoneChange = (e) => {
        let userInfo = this.state.userInfo;
        userInfo.cellPhone = e.target.value;
        this.setState({userInfo: userInfo});
    }

}

UserInfo.propTypes = {};

export default UserInfo;